<?php

namespace App\Http\Controllers;

use App\Models\CourseEvaluate;
use App\Models\UserSignUp;
use Illuminate\Http\Request;

class SignUpController extends BaseController
{

    public function signUp(Request $request, UserSignUp $userSignUp)
    {
        $userid = 1;
        $course_id = $request->post('course_id');

        $data = $userSignUp->getOne($userid, $course_id);
        if ($data) {
            return $this->failResponse('您已经报名了,无法重复操作,前往报名管理查看');
        }
        $data = $userSignUp->insert([
            'user_id' => $userid,
            'course_id' => $course_id,
            'status' => 1,
        ]);
        return $this->successResponse($data, '报名成功');
    }

    public function signUpList(Request $request, UserSignUp $userSignUp)
    {
        $query = $userSignUp::with('course.teacher.qualifications')->with('evaluate')->where('user_id', 1);
        if ($request->input('status') > 0) {
            $query->where('status', $request->input('status'));
        }
        $data = $query->orderByDesc('id')->paginate(10);
        return $this->successResponse($data);
    }

    public function signUpChangeStatus(Request $request, UserSignUp $userSignUp)
    {
        $userid = 1;
        $course_id = $request->post('course_id');
        $status = $request->post('status');

        $data = $userSignUp->getOne($userid, $course_id);
        if (!$data) {
            return $this->failResponse('您还未报名,无法取消报名');
        }
        if ($data->status == $status) {
            return $this->failResponse('当前状态与您操作的状态一致,无法操作');
        }
        $up = [
            'status' => $status,
        ];
        if ($status == 3) {
            $up['pay_time'] = now();
        }
        $data = $userSignUp->where('id', $data->id)->update($up);
        return $this->successResponse($data);
    }

    public function saveOrUpdateEvaluate(Request $request, CourseEvaluate $courseEvaluate)
    {
        $userid = 1;

        if ($request->post('id')) {
            $data = $courseEvaluate->where('id', $request->post('id'))->update([
                'content' => $request->post('content'),
                'star' => $request->post('star'),
            ]);
        } else {
            $data = $courseEvaluate->insert([
                'user_id' => $userid,
                'course_id' => $request->post('course_id'),
                'sign_up_id' => $request->post('sign_up_id'),
                'content' => $request->post('content'),
                'star' => $request->post('star'),
            ]);
        }
        return $this->successResponse($data);
    }

}
